package com.hust360.percent.activity;

import java.io.File;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.TextView;

import com.hust360.percent.PercentApplication;

public class WelcomActivity extends Activity {

	PercentApplication percentApplication;

	public static final String TAG = "WelcomActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		TextView textView = new TextView(this);
		textView.setText("welcome!\n");
		setContentView(textView);
		percentApplication = (PercentApplication) getApplication();

		Log.i(TAG, "oncreate -- > thread id: " + Thread.currentThread().getId());

		/*
		 * 检测程序是不是第一次运行
		 */
		if (percentApplication.getSharedPreferences().getBoolean(
				PercentApplication.APP_IS_FIRST_RUN, true)) {
			/*
			 * 启动第一次运行改程序时候的欢迎的activity
			 */
			Intent intent = new Intent(this, FirstRunActivity.class);
			startActivityForResult(intent, 0);
		} else {
			InflateViewThread thread = new InflateViewThread();
			thread.start();
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 0 && resultCode == RESULT_OK) {
			finish();
		} else if (requestCode == 1 && resultCode == RESULT_OK) {
			finish();
		}
	}

	private class InflateViewThread extends Thread {

		Handler handler = new Handler();

		@Override
		public void run() {

			Log.i(TAG, "in background thread -- > thread id: "
					+ Thread.currentThread().getId());
			File file = WelcomActivity.this.getDatabasePath("city.db");
			SQLiteDatabase db = SQLiteDatabase.openDatabase(
					file.getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY);
			percentApplication.setCityDB(db);

			// Cursor cursor = db.query("city", null, null, null, null, null,
			// null);
			// while (cursor.moveToNext()) {
			// StringBuffer buffer = new StringBuffer();
			// buffer.append( " id: " + cursor.getLong(0));
			// buffer.append( " name: " + cursor.getString(1));
			// buffer.append( " province id: " + cursor.getLong(2));
			// Log.i(TAG, buffer.toString());
			// }
			// cursor.close();
			handler.post(new Runnable() {

				@Override
				public void run() {
					Log.i(TAG, "in handler's post method -- > thread id: "
							+ Thread.currentThread().getId());
					Intent intent = new Intent(WelcomActivity.this,
							MainActivity.class);
					startActivityForResult(intent, 1);
				}
			});
		}
	}
}
